﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Data;

namespace DavidDB.ADO.Tools
{
    public class SqliteHelper
    {
        /*
         			<add name="connectionString" providerName="System.Data.Sqlite" connectionString="Data Source=|test.db3"/>
         */
        //数据库连接字符串
        public static readonly string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString.Split(new char[] { '|' })[0] + AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString.Split(new char[] { '|' })[1];

        // 用于缓存参数的HASH表
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        /// <summary>
        ///  给定连接的数据库用假设参数执行一个sql命令（不返回数据集）
        /// </summary>
        /// <param name="connectionString">一个有效的连接字符串</param>
        /// <param name="commandText">存储过程名称或者sql命令语句</param>
        /// <param name="commandParameters">执行命令所用参数的集合</param>
        /// <returns>执行命令所影响的行数</returns>
        internal static int ExecuteNonQuery(string cmdText, System.Data.SQLite.SQLiteConnection conn, System.Data.SQLite.SQLiteTransaction trans, params System.Data.SQLite.SQLiteParameter[] commandParameters)
        {
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            PrepareCommand(cmd, conn, trans, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            cmd.Dispose();
            //   conn.Close();
            //    conn.Dispose();
            return val;
        }

        /// <summary>
        /// 用执行的数据库连接执行一个返回数据集的sql命令
        /// </summary>
        /// <remarks>
        /// 举例: 
        ///  System.Data.SQLite.SQLiteDataReader r = ExecuteReader(connString, "PublishOrders", new System.Data.SQLite.SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的连接字符串</param>
        /// <param name="commandText">存储过程名称或者sql命令语句</param>
        /// <param name="commandParameters">执行命令所用参数的集合</param>
        /// <returns>包含结果的读取器</returns>
        internal static System.Data.SQLite.SQLiteDataReader ExecuteReader(string cmdText, System.Data.SQLite.SQLiteConnection conn, System.Data.SQLite.SQLiteTransaction trans, params System.Data.SQLite.SQLiteParameter[] commandParameters)
        {
            //创建一个SqlCommand对象
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            //在这里我们用一个try/catch结构执行sql文本命令/存储过程，因为如果这个方法产生一个异常我们要关闭连接，因为没有读取器存在，
            //因此commandBehaviour.CloseConnection 就不会执行
            try
            {
                //调用 PrepareCommand 方法，对 SqlCommand 对象设置参数
                PrepareCommand(cmd, conn, trans, cmdText, commandParameters);
                //调用 SqlCommand  的 ExecuteReader 方法
                //  cmdText.Debug();
                System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();

                //清除参数
                cmd.Parameters.Clear();
                return reader;
            }
            catch
            {
                //关闭连接，抛出异常
                //    conn.Close();
                //     conn.Dispose();
                throw;
            }
        }
        /// <summary>
        /// 返回一个DataSet数据集
        /// </summary>
        /// <param name="connectionString">一个有效的连接字符串</param>
        /// <param name="cmdText">存储过程名称或者sql命令语句</param>
        /// <param name="commandParameters">执行命令所用参数的集合</param>
        /// <returns>包含结果的数据集</returns>
        internal static DataSet ExecuteDataSet(string cmdText, System.Data.SQLite.SQLiteConnection conn, params System.Data.SQLite.SQLiteParameter[] commandParameters)
        {
            //创建一个SqlCommand对象，并对其进行初始化
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();

            PrepareCommand(cmd, conn, null, cmdText, commandParameters);
            //创建SqlDataAdapter对象以及DataSet
            System.Data.SQLite.SQLiteDataAdapter da = new System.Data.SQLite.SQLiteDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                //填充ds
                da.Fill(ds);
                // 清除cmd的参数集合
                cmd.Parameters.Clear();
                cmd.Dispose();
                //   conn.Close();
                //    conn.Dispose();
                // cmdText.Debug();
                return ds;
            }
            catch
            {
                //关闭连接，抛出异常
                cmd.Parameters.Clear();
                cmd.Dispose();
                //     conn.Close();
                //      conn.Dispose();
                throw;
            }
        }

        /// <summary>
        /// 用指定的数据库连接执行一个命令并返回一个数据集的第一列
        /// </summary>
        /// <remarks>
        /// 例如: 
        ///  Object obj = ExecuteScalar(connString, "PublishOrders", new System.Data.SQLite.SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个存在的数据库连接</param>
        /// <param name="commandText">存储过程名称或者sql命令语句</param>
        /// <param name="commandParameters">执行命令所用参数的集合</param>
        /// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
        internal static object ExecuteScalar(System.Data.SQLite.SQLiteConnection connection, System.Data.SQLite.SQLiteTransaction trans, string cmdText, params dynamic[] commandParameters)
        {
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            PrepareCommand(cmd, connection, trans, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            cmd.Dispose();
            //   connection.Close();
            //   connection.Dispose();
            //    cmdText.Debug();
            return val;
        }
        /// <summary>
        /// 将参数集合添加到缓存
        /// </summary>
        /// <param name="cacheKey">添加到缓存的变量</param>
        /// <param name="cmdParms">一个将要添加到缓存的sql参数集合</param>
        internal static void CacheParameters(string cacheKey, params System.Data.SQLite.SQLiteParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }
        /// <summary>
        /// 找回缓存参数集合
        /// </summary>
        /// <param name="cacheKey">用于找回参数的关键字</param>
        /// <returns>缓存的参数集合</returns>
        internal static System.Data.SQLite.SQLiteParameter[] GetCachedParameters(string cacheKey)
        {
            System.Data.SQLite.SQLiteParameter[] cachedParms = (System.Data.SQLite.SQLiteParameter[])parmCache[cacheKey];
            if (cachedParms == null)
                return null;
            System.Data.SQLite.SQLiteParameter[] clonedParms = new System.Data.SQLite.SQLiteParameter[cachedParms.Length];
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms = (System.Data.SQLite.SQLiteParameter[])((ICloneable)cachedParms).Clone();
            return clonedParms;
        }
        /// <summary>
        /// 准备执行一个命令
        /// </summary>
        /// <param name="cmd">sql命令</param>
        /// <param name="conn">Sql连接</param>
        /// <param name="trans">Sql事务</param>
        /// <param name="cmdText">命令文本,例如：Select * from Products</param>
        /// <param name="cmdParms">执行命令的参数</param>
        private static void PrepareCommand(System.Data.SQLite.SQLiteCommand cmd, System.Data.SQLite.SQLiteConnection conn, System.Data.SQLite.SQLiteTransaction trans, string cmdText, dynamic[] cmdParms)
        {
            //判断连接的状态。如果是关闭状态，则打开
            if (conn.State != ConnectionState.Open)
            {
                try
                {
                    conn.Open();
                }
                catch (Exception)
                {

                    conn.Open();
                }
            }
            //cmd属性赋值
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            //是否需要用到事务处理
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;
            //添加cmd需要的存储过程参数
            if (cmdParms != null && cmdParms.Length > 0)
            {
                foreach (System.Data.SQLite.SQLiteParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
    }
}
